package com.dog.basics.common.aspect;

import cn.hutool.core.date.DateUtil;
import com.dog.basics.common.annotation.ApiLog4j;
import com.dog.basics.common.util.HttpContextUtils;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;

/**
 * @description: 拦截日志log
 * @author: He
 * @date: Created in 2022/2/7 12:19
 * @version: 1.0
 * @modified By:
 */
@Aspect
@Configuration
@AllArgsConstructor
@Log4j2
public class ApiLog4gAspect {

    private static ThreadLocal<Long> startTime = new ThreadLocal();

    /**
     * 环绕记录日志
     */
    @Around("@annotation(apiLog4j)")
    public Object interceptor(ProceedingJoinPoint pjp, ApiLog4j apiLog4j) throws Throwable {
        startTime.set(DateUtil.current());
        return pjp.proceed();
    }

    /**
     * 结束环绕
     * @param apiLog4j
     */
    @AfterReturning("@annotation(apiLog4j)")
    public void doAfterReturing(ApiLog4j apiLog4j) {
        log.info("[正常]请求Url : {} 请求时间: {} 请求耗时：{}", HttpContextUtils.getHttpServletRequest().getRequestURL().toString(), DateUtil.formatDateTime(DateUtil.date(startTime.get())), (DateUtil.current() - startTime.get()));
    }

    /**
     * 异常环绕
     * @param e
     * @param apiLog4j
     */
    @AfterThrowing(value = "@annotation(apiLog4j)", throwing = "e")
    public void afterThrowing(Throwable e, ApiLog4j apiLog4j) {
        log.info("[异常]请求Url : {} 请求时间: {} 请求耗时：{}", HttpContextUtils.getHttpServletRequest().getRequestURL().toString(), DateUtil.formatDateTime(DateUtil.date(startTime.get())), (DateUtil.current() - startTime.get()));
    }
}
